package com.example.sys.async.handler.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.example.sys.async.po.SysASync;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/***
 * 阿里云短信发送服务
 */
public class AliSmsHandlerImpl extends AbstractASyncHandlerImpl {

    Logger logger = LoggerFactory.getLogger(getClass());

    private Client client;

    private String signName;

    private String accessKeyId;

    private String accessKeySecret;

    private String endpoint = "dysmsapi.aliyuncs.com";

    public String getSignName() {
        if (this.signName == null) {
            this.signName = getEnvironment().getProperty("sms.aliyun.signName");
        }
        return signName;
    }

    public String getAccessKeyId() {
        if (this.accessKeyId == null) {
            this.accessKeyId = getEnvironment().getProperty("sms.aliyun.accessKeyId");
        }
        return accessKeyId;
    }

    public String getAccessKeySecret() {
        if (this.accessKeySecret == null) {
            this.accessKeySecret = getEnvironment().getProperty("sms.aliyun.accessKeySecret");
        }
        return accessKeySecret;
    }

    public Client getClient() throws Exception {
        if (this.client == null) {
            com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config().setAccessKeyId(getAccessKeyId()).setAccessKeySecret(getAccessKeySecret());
            config.endpoint = endpoint;
            this.client = new com.aliyun.dysmsapi20170525.Client(config);
        }
        return this.client;
    }


    /***
     * 阿里云短信发送消息
     * @param sysASync
     * context 短信模板code
     * target 手机号
     * extraParameter 短信模板参数
     * @return
     */
    @Override
    public SysASync handler(SysASync sysASync) {
        try {
            com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                    .setPhoneNumbers(sysASync.getTarget())
                    .setSignName(getSignName())
                    .setTemplateCode(sysASync.getContext())
                    .setTemplateParam(sysASync.getExtraParameter());
            SendSmsResponse response = getClient().sendSms(sendSmsRequest);
            if (response.getBody().getMessage().equals("OK")) {
                sysASync.setSuccessed(true);
            } else {
                sysASync.setSuccessed(false);
                sysASync.setError(response.getBody().getMessage());
            }
        } catch (Exception e) {
            sysASync.setSuccessed(false);
            sysASync.setError(e.getMessage());
            logger.warn("aliyun sms send fail,target:{},error:{}", sysASync.getTarget(), e.getMessage());
        }
        return sysASync;
    }
}
